<template>
  <view class="page ui-form-basic">
		<view class="form-subtitle">商城管理</view>
		<view class="ask">
			<view class="ask-title">
				LOGO 上传要求
			</view>
			<view class="ask-content">
				LOGO 图片格式必须为：<text>png,bmp,jpeg,jpg,gif</text>；<text>不可大于2M</text>；建议使用 png 格式图片，以保持最佳效果；建议图片尺寸为 144px*144px。
			</view>
		</view>
    <fui-form ref="formRef" :model="form" class="form-wrapper" labelWidth="200" labelSize="28" labelWeight="bold">
      <fui-form-item label="LOGO" prop="mallLogo" left="0" marginTop="14" :padding="['16rpx', '32rpx']">
				<upload-image class="form-upload" type="avatar" @uploaded="uploadedLogo"  :defaultList="form.mallLogo ? [form.mallLogo] : []"></upload-image>
      </fui-form-item>
      <fui-form-item label="商城名称" prop="mallName" left="0" marginTop="14" :padding="['16rpx', '32rpx']">
        <fui-input minlength="4" maxlength="20" :borderBottom="false" :padding="[0]" v-model="form.mallName" placeholder="请输入商城名称" size="28"></fui-input>
      </fui-form-item>
      <fui-form-item label="商城简介" prop="mallBrief" left="0" marginTop="14" :padding="['16rpx', '32rpx']">
				<fui-textarea maxlength="120" isCounter :borderBottom="false" :padding="[0]" v-model="form.mallBrief" placeholder="请输入商城简介" size="28"></fui-textarea>
      </fui-form-item>
      <fui-form-item label="所属供应链" prop="scmId" left="0" marginTop="14" :padding="['16rpx', '32rpx']" :arrow="true">
				<fui-input :borderBottom="false" :padding="[0]" v-model="form.scmName" placeholder="请选择所属供应链" size="28" color="#999" disabled></fui-input>
      </fui-form-item>
      <fui-form-item label="状态" prop="status" left="0" marginTop="14" :padding="['16rpx', '32rpx']" :arrow="true" @click="showStatusPicker = true">
				<fui-tag text="停用" type="danger" theme="light" radius="36" v-if="form.status == 1"></fui-tag>
				<fui-tag text="启用" type="success" theme="light" radius="36" v-else></fui-tag>
      </fui-form-item>
      <fui-form-item label="主题方案" prop="themeColor" left="0" marginTop="14" :padding="['16rpx', '32rpx']" :arrow="true" @click="tab.navigateTo(themeLink)">
				<fui-input :borderBottom="false" :padding="[0]" v-model="currentTheme.title" placeholder="请选择主题方案" size="28" disabled></fui-input>
      </fui-form-item>
    </fui-form>
    <view class="btn-wrapper">
      <fui-button text="提交" height="78rpx" radius="8rpx" @click="handleSubmit"></fui-button>
    </view>

		<!-- 状态 -->
		<fui-picker layer="1" @cancel="showStatusPicker = false" radius :options="statusList" :linkage="true" :show="showStatusPicker"
        @change="onChangeStatus"></fui-picker>
  </view>
</template>

<script setup>
import { ref, computed, inject } from 'vue'
import { onLoad, onShow } from '@dcloudio/uni-app'
import { useStore } from 'vuex'
import uploadImage from '@/components/upload/image'
import mallApi from '@/api/mall'

const store = useStore()
const tab = inject('$tab')
const modal = inject('$modal')

const formRef = ref(null)
const form = ref({})
const rules = [
  {
    name: 'mallLogo',
    rule: ['required'],
    msg: ['请上传LOGO']
  },
  {
    name: 'mallName',
    rule: ['required', 'minLength:4', 'maxLength:20'],
    msg: ['请输入商城名称', '商城名称要求包含4~20个字符', '商城名称要求包含4~20个字符']
  },
  {
    name: 'mallBrief',
    rule: ['required', 'maxLength:120'],
    msg: ['请输入商城简介', '商城简介至多120个字符']
  },
	{
    name: 'scmId',
    rule: ['required'],
    msg: ['请选择所属供应链']
  }
]

// 获取主题详情
const currentTenant = computed(() => {
  return store.getters.tenantList.find(item => item.id === store.getters.currentTenantId)
})
const getMallConfig = () => {
  modal.loading('加载中...')
  mallApi.getMallConfig(store.getters.currentTenantId).then((res) => {
    modal.closeLoading()
    if (res.code === 0) {
      form.value = res.data || {
        status: 1,
        scmId: currentTenant.value.id,
        scmName: currentTenant.value.name
      }
      currentTheme.value = mallThemes.find(item => item.value === (form.value.themeColor || 'violet'))
    } else {
      modal.msgError('获取商城信息失败！')
    }
  }).catch(err => {
    modal.closeLoading()
    modal.msgError(err)
  })
}

// 上传LOGO
const uploadedLogo = (e) => {
	form.value.mallLogo = e[0] || ''
}

// 状态
const showStatusPicker = ref(false)
const statusList = ref([
	{ text: '启用', value: 0 },
	{ text: '停用', value: 1 },
])
const onChangeStatus = (e) => {
	showStatusPicker.value = false
	form.value.status = e.value
}

// 选择主题
const themeLink = computed(() => `/pages/mall/theme?currentTheme=${form.value.themeColor || 'violet'}`)
const { mallThemes } = store.getters
const currentTheme = ref({})
onLoad(() => {
  getMallConfig()
})
onShow(() => {
	uni.$once('onCheckedTheme', data => {
    form.value.themeColor = data
		currentTheme.value = mallThemes.find(item => item.value === data)
  })
})

// 保存商城配置
const handleSubmit = async () => {
  const res = await formRef.value.validator(form.value, rules)
	if (res.isPassed) {
    try {
      modal.loading()
      const apiUrl = form.value.id ? 'updateMallConfig' : 'addMallConfig'
      if (!form.value.themeColor) form.value.themeColor = 'violet'
      await mallApi[apiUrl](form.value)
      modal.closeLoading()
      modal.msgSuccess('商城配置保存成功!')
      setTimeout(() => {
        tab.navigateTo('/pages/index') 
      }, 1000)
    } catch(err) {
      modal.closeLoading()
      modal.msg(err)
    }
	}
}
</script>

<style lang="scss" scoped>
@import "@/static/scss/form.scss";

.form-subtitle {
	margin: 36rpx 0;
	font-size: 40rpx;
	font-weight: bold;
	color: #333333;
}

.ask {
	width: 100%;
	margin-bottom: 24rpx;
	padding: 22rpx 20rpx 24rpx 28rpx;
	border-radius: 24rpx 24rpx 24rpx 24rpx;
	background-color: #FFF3E4;
	box-sizing: border-box;

	.ask-title {
		font-size: 28rpx;
		font-family: PingFang SC, PingFang SC;
		font-weight: bold;
		color: #333333;
	}

	.ask-content {
		margin-top: 16rpx;
		font-size: 24rpx;
		font-family: PingFang SC, PingFang SC;
		font-weight: 400;
		color: #999999;

		text {
			color: #F95A5A;
		}
	}
}
</style>
